<template>
	<u-navbar :title="roomsName" :titleStyle="{
      'text-overflow': 'ellipsis',
      'white-space': 'nowrap',
      overflow: 'hidden',
    }" :autoBack="true" titleWidth="300rpx" height="100rpx">
	</u-navbar>
	<!-- 占位符 -->

	<view style="height: 80rpx"></view>
	<view style="height: 80rpx"></view>
	<!-- 内容区 -->
	<view class="Content">

		<scroll-view ref="scrollView" :scroll-top="scroll_top" scroll-y="true" id="scroll-Y" :show-scrollbar="true">
			<view class="item">
				<!-- <view class="Time" v-if="item.time">{{ item.time }}</view> -->
				<view class="MSG" v-for="child in messages" :key="child">
					<!-- 用户 -->
					<view class="list flex_s left" v-if="child.senderType == 1">
							<view class="Time">{{formatDate(child.sendTime)  }}</view>
						<view class="avatar mar_r">
							<image class="boder_r" :src="cleanUrl(child.senderAvatar)" mode="scaleToFill" />
						</view>

						<view class="desc flex_start">
							<image v-if="child.message.includes('http')" class="text-img" :src="cleanUrl(child.message)"
								@click="previewImage(cleanUrl(child.message))"
								@longpress="saveImage(cleanUrl(child.message))" alt="avatar" />
							<text v-else>{{ cleanUrl(child.message) }}</text>
						</view>
					</view>
					<!-- 骑手 -->
					<view class="list flex_s left" v-if="child.senderType == 5">
						<view class="Time">{{formatDate(child.sendTime)  }}</view>
						<view class="avatar mar_r">
							<image class="boder_r" :src="cleanUrl(child.senderAvatar)" mode="scaleToFill" />
						</view>

						<view class="desc flex_start">
							<image v-if="child.message.includes('http')" :src="cleanUrl(child.message)" alt="avatar"
								class="text-img" @click="previewImage(cleanUrl(child.message))"
								@longpress="saveImage(cleanUrl(child.message))" />
							<text v-else>{{ cleanUrl(child.message) }}</text>
						</view>
					</view>
					<!-- 商家 -->
					<view class="list flex_al_cen_ju_bet right" v-if="child.senderType == 4">
						<!-- 占位符 -->
						<view></view>
						<view class="Time">{{formatDate(child.sendTime)  }}</view>
						<view class="flex_s">
							<view class="desc flex_end">
								<image v-if="child.message.includes('http')" :src="cleanUrl(child.message)" alt="avatar"
									class="text-img" @click="previewImage(cleanUrl(child.message))"
									@longpress="saveImage(cleanUrl(child.message))" />
								<text v-else>{{ cleanUrl(child.message) }}</text>
							</view>
							<view class="avatar mar_l">
								<image class="boder_r" :src="child.senderAvatar" mode="scaleToFill" />
							</view>
						</view>
					</view>
				
				</view>
				<view class="ended" v-if="isMessage==false">
					当前聊天已结束
				</view>
			</view>
		</scroll-view>
	</view>

	<!-- 输入框 -->
	<view class="pos_f Footer">
		<view class="flex_al_cen_ju_bet Text">
			<view class="input">
				<u-input :customStyle="{ background: 'rgba(170,170,170,0.2)' }" placeholder="输入您对用户或骑手想说的话"
					border="surround" v-model="Content" :clearable="true"></u-input>
			</view>
			<div class="line" @click="afterRead">
				<u-icon name="plus" top="5px" bold color="#000" size="23"></u-icon>
			</div>
			<view class="Sumbit" @click="Sumbit">发送</view>
		</view>
	</view>
	<u-toast ref="uToast"></u-toast>
</template>

<script setup lang="ts">
	import { ref, onMounted, getCurrentInstance, reactive, onUnmounted } from "vue";
	import { onLoad } from "@dcloudio/uni-app";
	import { useWebSocket } from "@/Hooks/chat/chat.js";
	let scroll_top = ref();
	let list = reactive<any>([]);
	const messages = ref([]);
	const { proxy } = getCurrentInstance() as any;
	import * as $http from '@/utlis/interface/Wode'
	import { nowDate } from "@/utlis/time"
	// const { userInfo, getMyInfo, afterRead } = msg(proxy)
	const roomsName = ref();
	const OrderId = ref()
	// 连接到 WebSocket 并加入公共聊天室
	const authorization = uni.getStorageSync('Authorization')

	// 从 Authorization 字符串中提取 token
	const token = authorization.split(' ')[1];

	const constructWebSocketUrl = () => {
		if (OrderId.value) {
			const url = `wss://api.waimaishi.cn/websocket/message/${OrderId.value}/${token}/4`;
			return url;
		}
		return null; // 或者返回一个默认值
	};

	const { state, initSocket, sendMsg, closeSocket } = new useWebSocket();
	const isMessage = ref(true)
	let Content = ref("");
	let index = ref(0);
	const Sumbit = () => {
		if (!isMessage.value) {
			return proxy.$API(proxy).Toast("暂时无法通话", "warning");
		}
		if (!Content.value)
			return proxy.$API(proxy).Toast("请输入要发送的内容", "warning");
		index.value++;
		sendMsgs(Content.value);

		// 没任何意义的计时器 单纯就是为了做个延迟感觉
		setTimeout(() => {
			// 数据变了视图没变所以要数据改变后立马同步视图
			proxy.$nextTick(() => {
				scroll_top.value = 10000;
			});
		}, 500);
	};
	const cleanUrl = (url : any) => {
		// 去掉两边的引号
		return url.replace(/^['"]|['"]$/g, "");
	};

	onLoad((props : any) => {

		roomsName.value = props.roomsName.split('?')[0];;

		OrderId.value = props.id // 使用正则提取 id 后的数字
		// console.log(111,  props.roomsName )
		uni.setNavigationBarTitle({
			title: props.roomsName, // 这里可以是任何变量，例如通过 data 或 props 动态获取的值
		});
	});
	// 预览图片
	const previewImage = (url : string) => {
		uni.previewImage({
			current: url, // 当前显示图片的链接
			urls: [url] // 图片数组，支持多张图片一起预览
		});
	};
	const formatDate = (timestamp) => {
	    const date = new Date(timestamp);
	    const year = date.getFullYear();
	    const month = String(date.getMonth() + 1).padStart(2, '0');
	    const day = String(date.getDate()).padStart(2, '0');
	    const hours = String(date.getHours()).padStart(2, '0');
	    const minutes = String(date.getMinutes()).padStart(2, '0');
	    const seconds = String(date.getSeconds()).padStart(2, '0');
	    
	    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	};
	// 长按保存图片
	const saveImage = (url : string) => {
		uni.saveImageToPhotosAlbum({
			filePath: url,
			success: () => {
				uni.showToast({
					title: '保存成功',
					icon: 'success'
				});
			},
			fail: (err) => {
				uni.showToast({
					title: '保存失败',
					icon: 'error'
				});
				console.error('保存失败', err);
			}
		});
	};
	// 发送消息的封装
	const sendMsgs = (val : string) => {
		sendMsg(val)
			.then((res : any) => {
				console.log("发送成功:", res);
				Content.value = "";
			})
			.catch((error : any) => {
				console.log("发送失败:", error);
			});
	};
	const scrollView = ref();
	// 图片上传
	let userInfo = reactive<User>({
		realNameStatus: null,
		nickname: null,
		avatar: null,
	})

	const afterRead = (event : any) => {
		uni.chooseImage({
			sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
			success: ((chooseImageRes : any) => {
				userInfo.avatar = chooseImageRes.tempFilePaths[0]
				uni.showLoading({

				})

				uni.uploadFile({
					url: `https://api.waimaishi.cn/app-api/common/AppUpload`,
					name: 'file', //二进制文件
					filePath: chooseImageRes.tempFilePaths[0],
					header: {
						Authorization: uni.getStorageSync('Authorization'),
					},
					formData: {
						pathPrefix: 'rider' + nowDate()
					},
					success: (uploadFileRes : any) => {
						uni.hideLoading()
						let imgData = JSON.parse(uploadFileRes.data)
						sendMsgs(imgData.data);
						if (imgData.code == 0) {
							// userInfo.avatar = imgData.data
							// nowsAVATRA.infoData.userAvatar = imgData.data

							uni.hideLoading()
							proxy.$API(proxy).Toast('发送成功', 'success')
						} else {
							uni.hideLoading()
							proxy.$API(proxy).Toast(imgData.msg, 'error')
						}
					},
					fail: (err) => {
						uni.hideLoading()
						proxy.$API(proxy).Toast('上传上传失败', 'error')
					},
				})

			})
		})


	}
	// 打开文件选择框
	const openMediaPicker = () => {
		uni.chooseImage({
			count: 1,
			sizeType: ["original", "compressed"],
			sourceType: ["camera", "album"], //这要注意，camera是拍照，album是打开手机相册
			success: (res) => {
				afterRead(res.tempFiles);
			},
		});
	};
	// 存储上传图片的数组 添加图片
	// let pictureArr = [];
	// const afterRead = (file) => {

	//   AppUpload(file[0].path).then((res) => {
	// 	   console.log('选择的图片路径:', res.data); // 打印路径，检查是否正确
	//     sendMsgs(res.data);
	//     pictureArr.push(res.data);
	//   });
	// };
	onMounted(() => {
		const url = constructWebSocketUrl();
		if (url) {
			initSocket(url);
		} else {
			console.error("无法初始化 WebSocket: OrderId.value 为 undefined");
		}

		uni.$on("WS", (res) => {
			console.log(res);
			isMessage.value = res.isMessage
			// 如果 messages.length > 0，拼接新消息，否则直接覆盖
			if (messages.value.length > 0) {
				messages.value = [...messages.value, ...res.messageList];
				scroll_top.value = messages.value.length * 100;
			} else {
				messages.value = res.messageList;
			}
			// 更新 scroll_top
			proxy.$nextTick(() => {
				scroll_top.value = messages.value.length * 100; // 保证滚动到最底部
			});
		});
	});
	onUnmounted(() => {
		if (closeSocket) {
			closeSocket();
			console.log("WebSocket 已关闭");
		}
	});
</script>
<style lang="scss" scoped>
	@import "../../static/css/Message/Messagedetails.scss";

	.text-img {
		width: 100%;
		/* 让图片宽度自适应容器 */
		height: 200px;
		/* 根据宽度自动调整高度，保持比例 */

		object-fit: cover;
		/* 保证图片覆盖容器且不变形 */
		border-radius: 8px;
		/* 圆角效果 */
		box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
		/* 微妙的阴影效果 */
	}

	.line {
		border: 1px solid #000;
		border-radius: 50%;
		height: 35px;
		width: 35px;
		padding: 0 4px;
		margin-right: 5px;
		box-sizing: border-box;
	}
	.ended{
		text-align: center;
		    padding: 10px 0;
		    font-size: 14px;
		    color: #00000070;
	}
</style>